from apps.minapp import models
from rest_framework.response import Response
from rest_framework.views import APIView
from eatfun_backend import settings
from apps.minapp import models
import requests
import uuid
import hashlib
import time
from utils.jwt_auth import create_token


def create_uid(nickname):
    """
    生成随机字符串
    :param nickname:
    :return:
    """
    string = "{}-{}-{}".format(nickname, time.time(), str(uuid.uuid4()))
    md5_object = hashlib.md5(settings.SECRET_KEY.encode('utf-8'))
    md5_object.update(string.encode('utf-8'))
    return md5_object.hexdigest()


def getopenid(code):
    params = {
        'appid': settings.appid,
        'secret': settings.appsecret,
        'js_code': code,
        'grant_type': 'authorization_code'
    }
    result_dict = requests.get(settings.code2Session, params=params).json()
    return result_dict


class LoginView(APIView):
    authentication_classes = []
    # def post(self, request, *args, **kwargs):
    #     userid = request.data.get('userid')
    #     name = request.data.get('name')
    #     print(userid, name)
    #     wx_code = request.data.get('wx_code')
    #     params = {
    #         'appid': settings.appid,
    #         'secret': settings.appsecret,
    #         'js_code': wx_code,
    #         'grant_type': 'authorization_code'
    #     }
    #     result_dict = requests.get(settings.code2Session, params=params).json()
    #     users = models.User.objects.all()
    #     print(request.data.get('avatar'))
    #     userobj = users.filter(name=name, userid=userid)
    #     token = create_uid(userid + name)
    #     if not userobj:
    #         print(userobj)
    #         users.create(
    #             **result_dict,
    #             name=name,
    #             userid=userid,
    #             nickname=request.data.get('nickname'),
    #             token=token
    #             # avatar=request.data.get('avatar')
    #         )
    #     else:
    #         print('dddd')
    #
    #         userobj.update(
    #             **result_dict,
    #             nickname=request.data.get('nickname'),
    #             token=token
    #             # avatar=request.data.get('avatar')
    #         )
    #     return Response(result_dict)
    def post(self, request, *args, **kwargs):
        # 暂时使用网页端登录方式,
        admin = request.data
        print(admin)
        if admin['type'] == 'client':  # 如果是用户
            admins = models.User.objects.all()
            userinfo = admins.filter(studentid=admin['userid'])
            role = 'client'
        else:  # type = 'staff'
            admins = models.Staff.objects.all()
            userinfo = admins.filter(workid=admin['userid'])
            role = 'staff'
        # 如果注册过
        if userinfo.exists():
            print(userinfo)
            password = userinfo[0].password
            if admin['password'] == password:
                username = admin['userid']
                atoken = create_token(role, username, i_ex=3600)
                result_dict = getopenid(admin['code'])
                print(result_dict)
                print(len(atoken))
                userinfo.update(
                    token=atoken,
                    **result_dict
                )
                # rtoken = createToken(username, i_ex=1080)
                return Response(
                    {"code": 0, "msg": "登录成功", 'atoken': atoken})
            else:
                return Response({"code": -1, "msg": "学号或密码错误"})
        # 如果没有注册
        else:
            return Response({"code": -1, "msg": "账户不存在，请先注册"})


def getaccesstoken():
    params = {
        'appid': settings.appid,
        'secret': settings.appsecret,
        'grant_type': 'client_credential'
    }
    result_dict = requests.get(settings.getAccessToken, params=params).json()
    print(result_dict)
    access_token = result_dict['access_token']
    expires_in = result_dict['expires_in']
    return access_token, expires_in
